package org.xxx.epms.models.epms.controller;


import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import org.xxx.epms.common.api.CommonResult;
import org.xxx.epms.models.epms.dto.AdminParam;
import org.xxx.epms.models.epms.model.Admin;
import org.xxx.epms.models.epms.service.AdminService;
import java.util.HashMap;
import java.util.Map;

import static com.sun.xml.internal.ws.spi.db.BindingContextFactory.LOGGER;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lb
 * @since 2024-06-08
 */
@RestController
@RequestMapping("/epms/admin")
public class AdminController {

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Autowired
    private AdminService adminService;

    //写一个方法测试swagger
    @RequestMapping(value = "/test1",method = RequestMethod.GET )
    @ApiOperation(value = "测试swagger", notes = "测试swagger")
    public String test(){
        return "test1";
    }

    @RequestMapping(value = "/test2",method = RequestMethod.GET )
    @ApiOperation(value = "测试swagger", notes = "测试swagger")
    public String test0(){
        return "test2";
    }


    //注册用户接口
    @RequestMapping(value = "/register",method = RequestMethod.POST )
    @ApiOperation(value = "注册用户", notes = "注册用户")
    public CommonResult<Admin> register(@Validated @RequestBody AdminParam adminParam){
        Admin admin = adminService.register(adminParam);
        if (admin == null) {
            return CommonResult.failed();
        }
        return CommonResult.success(admin);
    }

    //登录接口
    @RequestMapping(value = "/login",method = RequestMethod.POST )
    @ApiOperation(value = "登录", notes = "登录")
    public CommonResult login(@Validated @RequestBody AdminParam adminParam) {
        String token = adminService.login(adminParam);
        if (token == null) {
            return CommonResult.validateFailed("用户名或密码错误");
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
        LOGGER.info("login success, token: " + token);
        return CommonResult.success(tokenMap);
    }

    //获取用户信息接口
    @RequestMapping(value = "/info",method = RequestMethod.POST )
    @ApiOperation(value = "获取用户信息", notes = "获取用户信息")
    public CommonResult<Admin> getAdminInfoByAdminCode(@RequestBody AdminParam adminParam) {
        Admin admin = adminService.getAdminByAdminCode(adminParam.getAdminCode());
        if (admin == null) {
            return CommonResult.failed("用户不存在");
        }
        admin.setAdminPassword(null);
        return CommonResult.success(admin);
    }

}

